package com.wt.struggle.goodbye.main.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.util.ArrayMap
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.*
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.ItemClickListener
import com.wt.struggle.goodbye.base.ProBaseAdapter
import com.wt.struggle.goodbye.base.ProV4Fragment
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.main.activity.SendTieActivity
import com.xin.lv.yang.utils.activity.PictureSelectorActivity
import com.xin.lv.yang.utils.info.PicItem
import com.xin.lv.yang.utils.permission.PermissionsManager
import com.xin.lv.yang.utils.photo.image.AlbumBitmapCacheHelper
import com.xin.lv.yang.utils.utils.BitmapUtil
import com.xin.lv.yang.utils.utils.ImageUtil
import kotlinx.android.synthetic.main.photo_layout.*

class PhotoFragment : ProV4Fragment() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.photo_layout, container, false)
    }

    var perWidth: Int = 0

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val windowManager = activity!!.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
        perWidth = (windowManager!!.defaultDisplay.width - BitmapUtil.dip2px(activity!!, 4.0f)) / 3

        if (savedInstanceState != null) {
            mAllItemList = savedInstanceState.getParcelableArrayList("ItemList")
        }

        AlbumBitmapCacheHelper.init(activity)

        val code1 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.READ_EXTERNAL_STORAGE)
        val code2 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.WRITE_EXTERNAL_STORAGE)

        if (code1 == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {
            init()
        } else {
            ActivityCompat.requestPermissions(
                activity!!,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ), 1234
            )
        }


    }

    override fun onSaveInstanceState(outState: Bundle) {
        if (mAllItemList != null && mAllItemList.size > 0) {
            outState.putParcelableArrayList("ItemList", mAllItemList)
        }

        super.onSaveInstanceState(outState)
    }

    override fun onDestroy() {

        mAllItemList.clear()
        super.onDestroy()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1234) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED
            ) {
                init()
            } else {
                showToastShort(activity!!, "请开启存储权限")
            }
        }
    }


    fun init() {

        updatePictureItems()

        initAdapter()
    }

    lateinit var picAdapter: GridViewAdapter

    var mAllItemList = arrayListOf<PicItem>()

    /**
     * 显示图片信息的adapter
     */
    fun initAdapter() {

        log("图片数量--------" + mAllItemList.size)

        val manager = LinearLayoutManager(activity)
        manager.orientation = LinearLayout.HORIZONTAL

        photoRecyclerView.layoutManager = manager
        picAdapter = GridViewAdapter(activity!!, mAllItemList)

        photoRecyclerView.adapter = picAdapter
        picAdapter.itemClickListener = object : ItemClickListener {

            override fun onItemClick(position: Int) {
                val picItem = mAllItemList[position]
                (activity as SendTieActivity).savePic(picItem)
            }

            override fun onLongClick(position: Int) {

            }

        }
    }


    /**
     * 获取本地图片信息
     */
    private fun updatePictureItems() {
        val projection = arrayOf("_data", "date_added")
        val orderBy = "datetaken DESC"
        val cursor = activity!!.contentResolver
            .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, orderBy)

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    val item = PicItem()
                    item.uri = cursor.getString(0)
                    if (item.uri != null) {
                        this.mAllItemList.add(item)
                    }
                } while (cursor.moveToNext())
            }
            cursor.close()
        }
    }


    inner class GridViewAdapter(context: Context, list: ArrayList<PicItem>) :
        ProBaseAdapter<PicItem>(context, list) {

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val vh = holder as ViewHolder
            val picItem = list[position]
            val w = getW(context) / 3

            vh.image!!.layoutParams = FrameLayout.LayoutParams(w, w)
            vh.photoFrameLayout.layoutParams = FrameLayout.LayoutParams(w, w)

            val pathh = picItem.uri

            val www = getW(context) / 3

            ImageUtil.getInstance()
                .loadRoundCircleImage(context, vh.image, pathh, R.drawable.rc_grid_image_default, 4, www, www)

//
//            if (vh.image!!.tag != null) {
//                val path = vh.image!!.tag as String
//                AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path)
//            }
//            AlbumBitmapCacheHelper.getInstance().addPathToShowlist(pathh)
//            vh.image!!.tag = pathh
//            val bitmap = AlbumBitmapCacheHelper.getInstance()
//                .getBitmap(
//                    pathh, perWidth, perWidth,
//                    AlbumBitmapCacheHelper.ILoadImageCallback { bitmap, path1, objects ->
//                        if (bitmap != null) {
//                            val bd = BitmapDrawable(activity!!.resources, bitmap)
//                            val v = photoRecyclerView.findViewWithTag<View>(path1)
//
//                            if (v != null) {
//                                v.background = bd
//                            }
//                        }
//                    }, Integer.valueOf(position)
//                )
//
//            if (bitmap != null) {
//                vh.image!!.setImageBitmap(bitmap)
//            } else {
//                vh.image!!.setBackgroundResource(R.drawable.rc_grid_image_default)
//            }
//

            vh.checkBox!!.visibility = View.GONE

        }

        override fun onCreateView(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return ViewHolder(inflater.inflate(R.layout.choose_photo_item, parent, false))

        }

        override fun onUpdateHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {

        }


        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            internal var image: ImageView? = view.findViewById(R.id.image)
            internal var checkBox: CheckBox? = view.findViewById(R.id.checkbox)
            val photoFrameLayout = view.findViewById<FrameLayout>(R.id.photoFrameLayout)
        }
    }

}